package com.zhiyizhen.handheld.common;

import com.zhiyizhen.handheld.common.sp.SpConstant;
import com.zhiyizhen.handheld.common.sp.SpUtil;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.api.IMainService;
import com.zhiyizhen.handheld.component.main.bean.EnumsBean;
import com.zhiyizhen.handheld.component.main.bean.MenuItemBean;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import java.util.List;

public class DataCache {

    private static LoginBean loginBean;
    private static EnumsBean enumsBean;
    private static List<MenuItemBean> menuList;

    public static LoginBean getLoginBean() {
        return loginBean;
    }

    public static void setLoginBean(LoginBean loginBean) {
        DataCache.loginBean = loginBean;
    }

    public static EnumsBean getEnumsBean() {
        if (enumsBean == null) {
            enumsBean = (EnumsBean) SpUtil.getObject(SpConstant.ENUMS_BEAN);
        }
        return enumsBean;
    }

    public static void saveEnumsBean(EnumsBean enumsBean) {
        DataCache.enumsBean = enumsBean;
        SpUtil.putObject(SpConstant.ENUMS_BEAN, enumsBean);
    }

    public static List<MenuItemBean> getMenuList() {
        if (menuList == null) {
            menuList = (List<MenuItemBean>) SpUtil.getObject(SpConstant.MENU_LIST);
        }
        return menuList;
    }

    public static void setMenuList(List<MenuItemBean> menuList) {
        SpUtil.putObject(SpConstant.MENU_LIST, menuList);
        DataCache.menuList = menuList;
    }

    public static void requestEnumsMap(CallBack callBack) {
        LoginBean loginBean = DataCache.getLoginBean();
        ServiceFactory.getService(IMainService.class)
                .getEnumsMap(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<EnumsBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            DataCache.saveEnumsBean(responseData.getData());
                            callBack.onSuccess();
                        }
                    }

                    @Override
                    protected void onFinally() {
                        super.onFinally();
                    }
                });
    }



    public interface CallBack {
        void onSuccess();
    }
}
